import React from "react";
import { Button } from 'antd';

/**
 * reducer-callback to create reducer
 * @param stateObj current state-obj
 * @param action update operator
 * @returns reduce-updator
 */
function reducer(stateObj: Record<string, any>, action: { type: string, payload: any }) {
    const rsl: Record<string, any> = {}
    rsl[action.type] = action.payload
    return rsl;
}

/**
 * global-state context
 */
const ctx = React.createContext({
    vars: {},
    setVar: (varName: string, value: any) => { }
});

/**
 * create initial-values of Provider-Component
 * @param globalState global-state object
 * @returns Initial-values of Provider-Component
 */
function initialValue(globalState: Record<string, any>) {
    const [vars, dispatch] = React.useReducer(reducer, globalState)
    const setVar = (varName: string, value: any) => { dispatch({ type: varName, payload: value }) }
    return { vars, setVar }
}

/**
 * Props of VarsProvider
 */
export interface VarsProviderProps {
    globalState: Record<string, any>
    children: React.ReactNode | undefined;
}

/**
 * VarsProvider-Component
 * @param props properties
 * @returns VarsProvider-Component
 */
export function VarsProvider(props: VarsProviderProps) {
    return (
        <ctx.Provider value={initialValue(props.globalState)}>
            {props.children}
        </ctx.Provider>
    )
}

export default ctx;